<?php
namespace Home\Model;
use Think\Model;

class SmsTemplateModel extends BaseModel {

	protected $tableName = 'tp_sms_template';

	/**
	 * @desc: 根据用户ID获取短信模板列表
	 * @Author: delayhsiao
	 * @update: 2016-11-26
	 **/
	public function getSmsTempList($userId){

        $defaultTemp = D('Home/User')->where(array('f_user_id'=>$userId))->field('f_template_id,f_professional')->find();

        //根据专业版状态获取模板
        if ( $defaultTemp['f_professional'] == 1 )
        {
            $template_since = 6;
        }
        else
        {
            $template_since = 0;
        }

	    $where = "`f_template_create_user`={$userId} OR (f_template_since={$template_since} and f_isGol=1 and f_template_status=1)";

		$templateList = $this->where($where)
			->field('
				f_template_content as fTemplateContent,
				f_template_create_time as fTemplateCreateTime,
				f_template_create_user as fTemplateCreateUser,
				f_template_id as fTemplateId,
				f_isGol as fIsDefault,
				f_template_since as fTemplateSince,
				f_template_type as fTemplateStatus,
				f_template_status as fTemplate
			')->select();

		foreach($templateList as $k => &$v){
            $v['type'] = '自定义模板';
            if ( ( $v['fTemplateSince'] == 0 || $v['fTemplateSince'] == 6 ) && $v['fIsDefault'] == 1 && $v['fTemplate'] == 1 ){
                $v['type'] = '系统模板';
            }

            //用户默认模板与模板id一致则手动改为默认模板
		    $v['fIsDefault'] = '1';
			if($v['fTemplateId'] == $defaultTemp['f_template_id']){
				$v['fIsDefault'] = '0';
			}
		}
		return $templateList;
	}

	/**
	 * @desc 获取默认模板
	 * @author quyang
	 * @update 2016-11-29
	 */
	public function getemplate( $id , $type = '0'){
	    //通过判断是否有模板id取得短信模板
	    if (!empty($id)){
	        //短信模板是否通过审核，没通过审核则调用系统模板
	        $data = $this->where(array('f_template_id'=>$id,'f_template_status'=>'1'))->find();
	        if($data == true){
                return $data;
            }
	    }
	    $where = array("f_template_since={$type} and f_isGol=1 and f_template_status=1 ");
	    $data = $this->where($where)->find();
	    return $data;
	}
}